package com.oc.mba.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.oc.mba.entity.OcDevices;
import com.oc.mba.service.DeviceService;
import com.oc.mba.util.CommConsts;
import com.oc.mba.util.CommLog;
import com.oc.mba.util.JsonUtil;
import com.oc.mba.util.ResultCode;

/**
 * 
 * 账户控制
 * @author unidw
 *
 */
@Controller
public class AccountController extends BaseController implements IController {

	private static final CommLog logger = new CommLog(AccountController.class);
	@Autowired
	private DeviceService deviceService;
	
	@Override
	public String progress(WrappedReq wReq, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("-------AccountController progress-----------");
		Map<String, Object> result = new HashMap<String, Object>();
		
		/** 注册客户端 **/
		if (wReq.getSignID().equals("100")) {
			String androidID = wReq.getContent().getString("androidID");
			String imei = wReq.getContent().getString("imei");
			logger.info("registerDevice. androidID=" + androidID + ", imei=" + imei);
			
			OcDevices device = deviceService.findByAndroidID(androidID);
			if (device!=null) {
				result.put(CommConsts.RESULT_FLAG, ResultCode.SUCCESS);
				result.put(CommConsts.DEVICE_ID, device.getId());
				result.put(CommConsts.VIP_LEVEL_KEY, device.getLevel());
				logger.info("Device has been Exist. deviceID=" + device.getId());
			}
			else {
				// 保存设备信息
				int deviceID = presistDevice(imei, androidID);
				if (deviceID > 0) {
					OcDevices deviceSaved = deviceService.findById(deviceID);
					result.put(CommConsts.RESULT_FLAG, ResultCode.SUCCESS);
					result.put(CommConsts.DEVICE_ID, deviceID);
					result.put(CommConsts.VIP_LEVEL_KEY, deviceSaved.getLevel());
					logger.info("Presist Device Success. deviceID=" + deviceID);
				}
				// 保存设备信息失败
				else {
					result.put(CommConsts.RESULT_FLAG, ResultCode.FAILURE);
					result.put(CommConsts.Result_DETAIL_FLAG, "Server Presist Failure");
					logger.info("Presist Device Failure. androidID=" + androidID + ", imei=" + imei);
				}
			}
		}
		else {
			logger.info("INVALID SignID. signID:" + wReq.getSignID());
			return genError(ResultCode.INVALID_REQ);
		}
		return JsonUtil.jsonMTS(result);
	}

	/**
	 * 保存设备
	 * @param imei 设备imei
	 * @param androidID androidID
	 * @return 
	 */
	private int presistDevice(String imei, String androidID) {
		return deviceService.presistDevice(imei, androidID);
	}
	
}
